package com.ithinks.flow.common.utils.protocol.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Description
 * @ClassName EchoServerHandler
 * @Author MR.LI
 * @date 2020.12.09 10:37
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    //服务端读取到网络数据后的处理
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*netty实现的缓冲区*/
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server Accept:"+in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
        ByteBufAllocator allocator = ctx.alloc();
        allocator.buffer();
        ctx.channel().alloc();
        ByteBuf buffer = Unpooled.buffer();
        Unpooled.directBuffer();
    }
    //服务端地区完成网络数据后处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //flush调所有的数据,flush完成关闭连接
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
    //发生异常后处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
